package com.jt.service;

import com.jt.vo.ImageVO;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@Service
public class FileServiceImpl implements FileService {
    @Value("${file.localDir}")
    private String localDir ;//属性动态赋值，spel表达式
    @Value("${file.urlPath}")
    private String urlPath;
        /**
         * 业务说明：
         *      1.校验图片类型
         *      2.防止恶意程序攻击
         *      3.分文件目录存储  hash   date
         *      4.重新设定文件名称UUID
         *      5.实现文件的上传
         *      6.封装VO对象之后返回
         */

    @Override
    @Transactional
    public ImageVO upLoad(MultipartFile file) {
//        1.校验图片类型
        String fileName = file.getOriginalFilename();
        fileName =fileName.toLowerCase();
        if (!fileName.matches("^.+\\.(jpg|png|gif)$")){
            return null;
        }
        try {
            BufferedImage bufferedImage=ImageIO.read(file.getInputStream());
      int width= bufferedImage.getWidth();
       int height =bufferedImage.getHeight();
       if(width==0||height==0){
           return null;
       }
        } catch (IOException e) {
            e.printStackTrace();
            return null;
//            如果有错，就报错返回
        }
//        分目录存储，将当前时间格式化
       String dateDir= new SimpleDateFormat("/yyyy/MM//dd/").format(new Date());
        String fileDir = localDir+dateDir;
        File dirFile = new File(fileDir);
        if (!dirFile.exists()){
            dirFile.mkdirs();
        }
//        动态生成UUID
        String uuid = UUID.randomUUID().toString().replace("-", "");
       int index = fileName.lastIndexOf(".");
        String fileType = fileName.substring(index);
        String realFileName = uuid +fileType;
//        5实现文件上传，文件目录/文件名称 C:/Users/tarena/Pictures/2021/6/17/uuid.jpg
        String realFilePath =fileDir+realFileName;
        try {
            file.transferTo(new File(realFilePath));
            ImageVO imageVO = new ImageVO();
//           存储文件磁盘地址
            imageVO.setVirtualPath(realFilePath);
//            指定文件名字
            imageVO.setFileName(realFileName);
//            设定网络访问地址
            String url=urlPath+dateDir+realFileName;
            imageVO.setUrlPath(url);
            return imageVO;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }

    }
}
